<template>
  <div class="chat-container">
    <div class="back-content">
      <input
        type="text"
        style="width: 0;height: 0;position:absolute; left: -100%;top: 0;"
        id="reset"
        ref="reset"
      />
      <section
        class="chatlist"
        :class="showSelBox ? 'chatlist-bottom-collapse' : 'chatlist-bottom'"
        @click.self="handelBlur"
      >
        <mt-loadmore :top-method="loadTop" ref="loadmore">
          <ul>
            <div class="showTips" v-show="showTips">你们已经是好友了，可以发送消息聊天了</div>
            <template v-for="(item,i) of recordList">
              <li :key="i" class="chat-mine" v-if="item.isMeSend === 1">
                <div class="chat-user">
                  <img :src="sendUserIcon" />
                </div>
                <div class="time">
                  <cite>
                    <i>{{item.createTime}}</i>
                    {{item.name}}
                  </cite>
                </div>
                <div class="chat-text">{{item.content}}</div>
              </li>
              <li :key="i" v-if="item.isMeSend !== 1">
                <div class="chat-user">
                  <img :src="friendIcon" />
                </div>
                <div class="time">
                  <cite>
                    {{/*item.name*/}}
                    <i>{{item.createTime}}</i>
                  </cite>
                </div>
                <div class="chat-text">{{item.content}}</div>
              </li>
            </template>
          </ul>
        </mt-loadmore>
      </section>
    </div>
    <section class="foot">
      <!--<mt-field id="txtContent" placeholder="请输入消息" class="con" v-model="content" @input="onInput($event)"/>-->

      <div class="input-line">
        <span class="btn-face" @click="showSelBox = !showSelBox">
          <img src="./images/smile.png" class="smile" />
        </span>
        <div class="input-wrapper">
          <input
            id="txtContent"
            placeholder="请输入消息"
            class="con"
            v-model="content"
            @input="onInput($event)"
            @blur="onBlur($event)"
          />
        </div>
        <span class="btn btn-send" @click="sendMsg" :class="sendClass">发送</span>
      </div>

      <section class="selbox" v-show="showSelBox">
        <section v-show="showSelBox" class="face-box">
          <mt-swipe :auto="0" :continuous="false">
            <mt-swipe-item :key="n" v-for="n of Math.ceil(Emoji.length / pageEmojiNums)">
              <li :key="`${n}-${index}`" v-for="(emoji, index) of getEmoji(n, pageEmojiNums)">
                <span @click="addEmoji(emoji)">{{emoji}}</span>
              </li>
            </mt-swipe-item>
          </mt-swipe>
        </section>
      </section>
    </section>
    <slot />
  </div>
</template>

<script>
import { Toast } from 'mint-ui'

export default {
  name: 'a9-chat',
  props: {
    pageEmojiNums: {
      // 每页表情数量
      type: Number,
      default: 21
    },
    records: {
      // 聊天记录
      type: Array
    },
    Interval: {
      type: Number,
      default: 20000
    },
    ws: {
      type: String,
      required: true
    },
    friendUserId: {
      // 聊天对方id
      type: String,
      required: true
    },
    friendUsername: {
      // 聊天对方nickName
      type: String,
      required: true
    },
    friendIcon: {
      // 聊天对方icon
      type: String,
      required: true
    },
    sendUserId: {
      // 当前自己id
      type: String,
      required: true
    },
    sendUserIcon: {
      // 当前自己icon
      type: String,
      required: true
    },
    Emoji: {
      type: Array,
      default: () => [
        '😀',
        '😁',
        '😂',
        '😃',
        '😄',
        '😅',
        '😆',
        '😉',
        '😊',
        '😋',
        '😎',
        '😍',
        '😘',
        '😗',
        '😙',
        '😚',
        '😇',
        '😐',
        '😑',
        '😶',
        '😏',
        '😣',
        '😥',
        '😮',
        '😯',
        '😪',
        '😫',
        '😴',
        '😌',
        '😛',
        '😜',
        '😝',
        '😒',
        '😓',
        '😔',
        '😕',
        '😲',
        '😷',
        '😖',
        '😞',
        '😟',
        '😤',
        '😢',
        '😭',
        '😦',
        '😧',
        '😨',
        '😬',
        '😰',
        '😱',
        '😳',
        '😵',
        '😡',
        '😠'
      ]
    },
    sendClass: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      showSelBox: false, // 隐藏/显示表情
      content: '',
      recordList: [],

      socket: null,

      lastMsgId: null, // 最后一个消息ID，第一页传null
      showTips: false,
      input: null,
      resetInput: null,

      timer: null,
      cursor: null
    }
  },
  created () {
    // console.log(this.records)
    console.dir(this.$parent)
    if (!this.records) {
      // 未传入聊天记录列表
    } else {
      this.recordList = [...this.records]
    }
  },
  mounted () {
    this.socketInit()
  },
  methods: {
    getEmoji (pageNow, pageSize) {
      // 表情分页
      return this.Emoji.slice((pageNow - 1) * pageSize, pageSize * pageNow)
    },
    addEmoji (emoji) {
      // console.log(emoji)
      const len = this.content.length
      // console.log(len)
      // console.log(this.cursor)
      this.content =
        this.content.slice(0, this.cursor) +
        emoji +
        this.content.slice(this.cursor, len)
      this.cursor += 2
    },
    handelBlur () {
      this.showSelBox = false
    },
    loadTop (id) {
      // 上拉加载历史
      setTimeout(() => {
        if (!this.lastMsgId) {
          this.$refs.loadmore.onTopLoaded(id)
        }
      }, 1500)
    },
    sendMsg () {
      // 发送消息
      if (!this.content) {
        Toast('请输入消息')
        return
      }

      const messageData = {
        action: 2,
        chatMessage: {
          acceptUserId: this.$route.query.friendUserId,
          sendUserId: this.$route.query.atId || this.$route.query.sa_id,
          content: this.content
        },
        extand: ''
      }

      this.socket && this.socket.send(JSON.stringify(messageData))
      // console.log(this.records);
      // this.records.push();
      this.recordList.push({
        acceptUserId: this.friendUserId,
        content: this.content,
        isMeSend: 1,
        sendUserId: this.sendUserId,
        createTime: this.formatTime(new Date(), 'yyyy-MM-dd hh:mm')
      })

      this.content = ''

      this.scrollToBottom()
      // this.focusTxtContent();//聚焦输入框
      this.$refs.reset.focus()
      this.$refs.reset.blur()
    },

    focusTxtContent () {
      // 聚焦输入框
      document.querySelector('#txtContent input').focus()
    },

    scrollToBottom () {
      // 滚动条滚动到底部
      setTimeout(() => {
        const chatlist = document.getElementsByClassName('chatlist')[0]
        chatlist.scrollTop = chatlist.scrollHeight
      }, 100)
    },
    socketInit () {
      // 初始化socket
      if (window.WebSocket) {
        this.socket = new WebSocket(this.ws)
        this.socket.onopen = () => {
          console.log('客户端与服务端建立连接成功')
          const messageData = {
            action: 1,
            chatMessage: {
              // acceptUserId: this.$route.query.friendUserId,
              acceptUserId: this.friendUserId,
              // sendUserId: this.$route.query.atId || this.$route.query.sa_id,
              sendUserId: this.sendUserId,
              content: ''
            },
            extand: ''
          }
          this.socket.send(JSON.stringify(messageData))
          this.scrollToBottom()

          // 心跳包
          this.timer = setInterval(() => {
            const messageData = {
              action: 4,
              chatMessage: {
                acceptUserId: this.$route.query.friendUserId,
                sendUserId: this.$route.query.atId || this.$route.query.sa_id,
                content: ''
              },
              extand: ''
            }
            this.socket && this.socket.send(JSON.stringify(messageData))
          }, this.Interval)
        }
        this.socket.onmessage = e => {
          console.log('接收到消息')
          // console.log(JSON.parse(e.data));
          const result = JSON.parse(e.data)
          if (result.action === 2) {
            this.sign(
              result.chatMessage.acceptUserId,
              result.chatMessage.msgId
            )
            this.recordList.push({
              ...result.chatMessage,
              isMeSend: 0,
              name: this.friendUsername
            })
            // console.log(this.records);
            this.scrollToBottom()
          } else if (result.action === 3) {
          }
        }
        this.socket.onerror = e => {
          console.log(e)
          console.log('发生错误')
        }
        this.socket.onclose = e => {
          console.log(e)
          console.log('客户端与服务端关闭连接成功')
          // ..
        }
      }
    },
    sign (userId, msgId) {
      // 签收消息
      const messageData = {
        action: 3,
        chatMessage: {
          acceptUserId: userId,
          sendUserId: '',
          content: ''
        },
        extand: msgId
      }
      this.socket && this.socket.send(JSON.stringify(messageData))
    },

    onInput (e) {
      // console.log(e)
      const { selectionStart, selectionEnd } = e.target
      if (
        typeof selectionStart === 'number' &&
        typeof selectionEnd === 'number'
      ) {
        this.cursor = selectionStart
      }
    },
    onBlur (e) {
      // console.log(e)
      const { selectionStart, selectionEnd } = e.target
      if (
        typeof selectionStart === 'number' &&
        typeof selectionEnd === 'number'
      ) {
        this.cursor = selectionStart
      }
    },

    formatTime (date, pattern = 'yyyy-MM-dd') {
      function padding (s, len) {
        return (s + '').padStart(Math.max(2, len - (s + '').length), '0')
      }

      return pattern.replace(/([yMdhsm])(\1*)/g, $0 => {
        switch ($0.charAt(0)) {
          case 'y':
            return padding(date.getFullYear(), $0.length)
          case 'M':
            return padding(date.getMonth() + 1, $0.length)
          case 'd':
            return padding(date.getDate(), $0.length)
          case 'w':
            return date.getDay() + 1
          case 'h':
            return padding(date.getHours(), $0.length)
          case 'm':
            return padding(date.getMinutes(), $0.length)
          case 's':
            return padding(date.getSeconds(), $0.length)
        }
      })
    }
  },
  beforeDestroy () {
    clearInterval(this.timer)
    // this.socket && this.socket.close()
  },
  destroyed () {
    // console.log(this.socket)
    this.socket && this.socket.close()
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
::v-deep .mint-loadmore-text {
  color: rgba(255, 255, 255, 0.7);
  font-size: 30px;
}

.chat-container {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #f2f2f2;
}

.chatlist {
  position: absolute;
  top: 0;
  bottom: 100px;
  left: 0;
  right: 0;
  overflow-y: scroll;
  overflow-x: hidden;
  padding: 0 30px;
}

.chatlist-bottom {
  bottom: 220px;
}

.chatlist-bottom-collapse {
  bottom: 500px;
}

.chatlist ul {
  min-height: 300px;
}

.chatlist ul .chat-mine {
  text-align: right;
  padding-left: 20px;
  padding-right: 130px;
}

.chatlist ul li {
  position: relative;
  margin-bottom: 50px;
  padding-left: 130px;
  padding-right: 20px;
  min-height: 68px;
}

.chat-mine .chat-user {
  left: auto;
  right: 3px;
}

.chat-user {
  position: absolute;
  left: 3px;
}

.chat-text,
.chat-user {
  display: inline-block;
  vertical-align: top;
}

.chat-user img {
  width: 94px;
  height: 94px;
  border: 2px solid rgb(255, 255, 255);
  border-radius: 50%;
}

.time {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #fff;
  font-size: 28px;
}

cite {
  left: auto;
  right: 60px;
  text-align: right;
}

cite {
  font-style: normal;
  line-height: 24px;
  white-space: nowrap;
  text-align: left;
  font-size: 28px;
  color: #999;
  width: 100%;
}

cite i {
  font-style: normal;
  padding-left: 5px;
  padding-right: 5px;
  font-size: 22px;
}

.chat-mine .chat-text {
  margin-left: 0;
  text-align: left;
  background-color: #b3d7fa;
  color: #103a62;
  opacity: 0.8;
}

.chat-text {
  position: relative;
  line-height: 44px;
  margin-top: 15px;
  padding: 10px 15px;
  background-color: #fff;
  border-radius: 8px;
  color: #333;
  word-break: break-all;
  max-width: 390px;
}

.chat-text,
.chat-user {
  display: inline-block;
  vertical-align: top;
  font-size: 33px;
}

.chat-text img {
  max-width: 100%;
  vertical-align: middle;
}

.chat-user {
  position: absolute;
  left: 3px;
  top: 30px;
}

.chat-text:after {
  content: "";
  position: absolute;
  left: -15px;
  top: 15px;
  width: 0;
  height: 0;
  border-style: solid dashed dashed;
  border-color: #fff transparent transparent;
  overflow: hidden;
  border-width: 15px;
}

.chat-mine {
  .chat-text:after {
    left: auto;
    right: -15px;
    border-top-color: #b3d7fa;
  }
}

.foot {
  width: 100%;
  min-height: 94px;
  position: absolute;
  bottom: 0;
  left: 0;
  padding-top: 12px;
  display: flex;
  flex-direction: column;
}

::v-deep .mint-cell {
  height: 70px;
  max-height: 70px;
  min-height: 70px;
  border-radius: 35px;
}

::v-deep .mint-cell-wrapper {
  font-size: 28px;
  height: 60px;
}

.face-box {
  padding: 30px 15px 0;
  overflow: hidden;
  width: 700px;
  margin: 0 auto;
  height: 360px;
  box-sizing: border-box;
}

.face-box li {
  width: 69px;
  height: 90px;
  float: left;
  padding: 0 13px;
  list-style: none;
  font-size: 60px;
}

.btn {
  display: inline-block;
  vertical-align: middle;
  font-size: 40px;
  line-height: 40px;
  margin-left: 5px;
  padding: 0 6px;
  /*background-color: #33DF83;*/
  color: #fff;
  border-radius: 3px;
}

.btn-send {
  padding: 0 30px;
  font-size: 33px;
  color: #108ee9;
  display: flex;
  align-items: center;
}

.showTips {
  font-size: 27px;
  text-align: center;
  color: #103a62;
  opacity: 0.8;

  &.nv {
    color: #56233b;
  }
}

::v-deep .mint-swipe-indicators {
  height: 20px;
  bottom: -20px;

  .mint-swipe-indicator {
    width: 10px;
    height: 10px;
    top: -80px;
    position: relative;
  }
}

.smile {
  width: 54px;
  height: 54px;
  margin-left: 20px;
  margin-right: 20px;
}

.input-line {
  display: flex;
  height: 70px;
  justify-content: center;

  .input-wrapper {
    flex: 1;
    position: relative;
    display: flex;
    align-items: center;

    #txtContent {
      width: 100%;
      height: 60px;
      outline: 0;
      border: 0;
      padding: 0 15px;
    }
  }
}

.btn-face {
  display: flex;
  align-items: center;
}
</style>
